package com.manage.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.manage.utils.FBJSONResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(value = "有关图片上传的接口", tags = {"有关图片上传的接口"})
public class ImageUploadController {

    @ApiOperation(value = "图片上传", notes = "图片上传的接口")
    @ApiImplicitParam(name = "imageType", value = "图片类别", required = true, dataType = "String", paramType = "query")
    @PostMapping("/imageUpload")
    public FBJSONResult userUploadFace(String imageType, @RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws Exception {
        //文件保存的名密空间
        String fileSpace = "D:/Development/program/shoes_bfrond/src/images";
        String hostUrl = "http://127.0.0.1:8081/images";
        //保存到数据库中的相对路径
        String userUploadPathDB = "/" + imageType;
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        try {
            if(files != null && files.length > 0) {
                //file的名字
                String originalFileName = files[0].getOriginalFilename();
                String extName = originalFileName.substring(originalFileName.lastIndexOf("."));
                String fileName = UUID.randomUUID() + extName;
                if(StringUtils.isNoneBlank(fileName)) {
                    //文件上传的最终保存路径
                    String finalFacePath = fileSpace + userUploadPathDB + "/" + fileName;
                    //设置数据库保存的路径
                    userUploadPathDB = hostUrl + userUploadPathDB + "/" + fileName;
                    File outFile = new File(finalFacePath);
                    if(outFile.getParentFile() != null || outFile.getParentFile().isDirectory()) {
                        //创建父文件夹
                        outFile.getParentFile().mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = files[0].getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                }
            } else {
                return FBJSONResult.errorMsg("上传出错。。。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return FBJSONResult.errorMsg("上传出错。。。");
        } finally {
            if(fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }
        return FBJSONResult.ok(userUploadPathDB);
    }

}
